#!/bin/bash
set -e

if [ $# -lt 1 ]; then
  echo "Usage: install.sh <USERNAME> [THREADS]"
  exit 1
fi

username="$1"
if [ -z "$2" ]; then
  threads=$(($(nproc) - 2))
else
  threads="$2"
fi

package="qli-Client-3.3.8-Linux-x64.tar.gz"
worker="$(hostname)"

path="/q"
xmrigBinary="xmrig-qlab"
serviceScript="qlab-Service.sh"
servicePath="/etc/systemd/system"
serviceName="qlab.service"
settingsFile="appsettings.json"
defaultToken="eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJJZCI6ImQzNzMyODc2LTY5ZDctNGI1OC1hNmUzLWM2MzZkMGQ4ZDE0NiIsIk1pbmluZyI6IiIsIm5iZiI6MTcyNTM3NjkyOSwiZXhwIjoxNzU2OTEyOTI5LCJpYXQiOjE3MjUzNzY5MjksImlzcyI6Imh0dHBzOi8vcXViaWMubGkvIiwiYXVkIjoiaHR0cHM6Ly9xdWJpYy5saS8ifQ.sregOyk2PEyXv8ssdQDBtTps1JFBLghcJCzDFvaD6hWoVA_T-crfQZbiV0E_atqd6sxNHYKGmeVCOoU9crLU4mnojZdF1vyp3VttB3ZIqo3qIgr0R4jWnwZ95bGN1c6NE3zb9y7ZWor5-4ttLkR_5moxiZZvaKG2WWSxFJ-7kk6SVSw7z8iaYyVpPX1Tdu6pBWxDStYYaoVvgNzx6RShU_r2AVCB1JGfv16vKvAIGmPcluvS-ayKwfgOpY1uEbsH6Lswd_KGbB1aJC7g8AI1CUoYiUUl_CJUBZfG0FbBgtGDRhfPUcYM5z8BEyIrm6bfKhMHuJmIF86NJYydRUHgow"

systemctl stop $serviceName 2>/dev/null || true

mkdir -p $path
cd $path
rm -f qli-Client xmrig-qlab *.tar.gz *.lock *.sol *.e*

# Check and download qli-client only if version mismatch
if [[ -f "qli-Client" ]]; then
  existing_version=$(./qli-Client --version 2>/dev/null | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+')
else
  existing_version=""
fi

expected_version="${package//qli-Client-/}"
expected_version="${expected_version//-Linux-x64.tar.gz/}"

if [[ "$existing_version" != "$expected_version" ]]; then
  echo "⬇️  Downloading QLI Client..."
  wget -4 -O "$package" "https://gitee.com/yesjh/minerlab/releases/download/v0.0.1/$package"
  tar -xzvf "$package"
  rm -f "$package"
  chmod +x qli-Client
else
  echo "✅ qli-Client v$existing_version already exists, skipping download."
fi

# Always redownload xmrig
wget -4 -O "$xmrigBinary" "https://gitee.com/yesjh/minerlab/releases/download/v0.0.1/$xmrigBinary"
chmod +x xmrig-qlab

# Generate appsettings.json with literal thread count
cat > "$settingsFile" <<EOF
{
  "ClientSettings": {
    "poolAddress": "wss://pps.minerlab.io/ws/$username",
    "alias": "$worker",
    "accessToken": "$defaultToken",
    "qubicAddress": null,
    "pps": true,
    "trainer": {
      "cpu": true,
      "gpu": false,
      "cpuVersion": "AVX512",
      "gpuVersion": "CUDA",
      "cpuThreads": $threads
    },
    "xmrSettings": {
      "disable": false,
      "enableGpu": false,
      "poolAddress": "qxmr.minerlab.io:3333",
      "customParameters": "-a rx/0 -u $username.$worker",
      "binaryName": "xmrig-qlab"
    },
    "idling": {
      "command": "",
      "arguments": ""
    }
  }
}
EOF

# Create runner
cat > "$serviceScript" <<EOF
#!/bin/bash
cd "$path"
./qli-Client
EOF
chmod +x "$serviceScript"

# Create systemd service
cat > "$servicePath/$serviceName" <<EOF
[Unit]
Description=QLAB Miner Service
After=network-online.target

[Service]
ExecStart=/bin/bash $path/$serviceScript
WorkingDirectory=$path
StandardOutput=null
StandardError=append:/var/log/qlab.error.log
Restart=on-failure
RestartSec=3


[Install]
WantedBy=multi-user.target
EOF

chmod 664 "$servicePath/$serviceName"
systemctl daemon-reload
systemctl enable "$serviceName"
systemctl start "$serviceName"

echo "✅ QLAB Miner installed and running."
echo "Username: $username"
echo "Worker: $worker"
echo "Threads: $threads"
